Value Types vs. Reference Types
Some C# specific info here...
Explain the differences between value type and reference type.
Interview Question
The main differences between value type and reference type are given below:
- A Value Type holds the actual data directly within the memory location and a Reference Type contains a pointer which consists of the address of another memory location that holds the actual data.
- Value type stores its contents on the stack memory and reference type stores its contents on the heap memory.
- Assigning a value type variable to another variable will copy the value directly and assigning a reference variable to another doesn’t copy the value, instead, it creates a second copy of the reference.
- Predefined data types, structures, enums are examples of value types. Classes, Objects, Arrays, Indexers, Interfaces, etc are examples of reference types.
Boxing:
Value type -> reference type Boxing is implicit.
Unboxing:
Reference type -> value type Unboxing is explicit.
An example is given below to demonstrate boxing and unboxing operations:
int a = 10; // a value type
object o = a; // boxing
int b = (int)o; // unboxing